<template>
  <div class="containers">
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" icon="el-icon-plus" class="handle-add mr10" @click="addregion"
          size="small">添加</el-button>
      </div>

      <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header"
        @selection-change="handleSelectionChange" v-loading="loading">
        <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="jurisdiction" label="标签"></el-table-column>
        <el-table-column label="操作" width="480" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="red"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button type="text" icon="el-icon-edit" @click="opendrawer(scope.row.ID)">api权限</el-button>
            <el-button type="text" icon="el-icon-edit" @click="openmenu(scope.row)">菜单权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
          :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑/添加弹出框 -->
    <el-dialog :title="type ? '编辑' : '添加'" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="姓名"><el-input v-model="form.name"></el-input></el-form-item>
        <el-form-item label="电话"><el-input v-model="form.mobile"></el-input></el-form-item>
        <el-form-item label="密码"><el-input v-model="form.password"></el-input></el-form-item>
        <el-form-item label="标签"><el-input v-model="form.jurisdiction"></el-input></el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置api权限 -->
    <el-drawer :visible.sync="drawer" title="I am the title" :with-header="false">
      <div class="drawerbox">
        <div class="drawerboxs">
          <el-tree :data="apiLIst" show-checkbox default-expand-all node-key="brief" ref="tree" highlight-current
            :props="defaultProps" :default-checked-keys="checklist">
          </el-tree>
          <el-button type="primary" class="handle-add mr10" @click="checkchange" size="small">修改</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 设置菜单权限 -->
    <el-drawer :visible.sync="menuShow" title="I am the title" :with-header="false">
      <div class="drawerbox">
        <div class="drawerboxs">
          <el-tree :data="menuLIst" show-checkbox default-expand-all node-key="name" ref="trees" highlight-current
            :props="menudefaultProps" :default-checked-keys="menuchecklist">
          </el-tree>
          <el-button type="primary" class="handle-add mr10" @click="checkchanges" size="small">修改</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  name: 'basetable',
  data() {
    return {
      form: {
        mobile: '',
        name: '',
        password: '',
        jurisdiction: ''
      },
      query: {
        pageIndex: 1,
         pageSize: 20
      },
      upimg: {
        token: '',
        key: new Date().valueOf()
      },
      code: 0,
      upload: '',
      tableData: [],
      multipleSelection: [],
      editVisible: false,
      pageTotal: 0,
      imageUrl: '',
      type: 0,
      drawer: false,
      menuShow:false,
      apiLIst: [],
      defaultProps: {
        children: 'children',
        label: 'brief'
      },
      menuLIst: [],
      menudefaultProps: {
        children: 'children',
        label: 'name'
      },
      menuchecklist: [],
      checklist: [],
      user: 0,
      loading:false,
      menucnst:[]
    };
  },
  created() {

    localStorage.setItem('routes',JSON.stringify(this.$router.options.routes))
    this.menucnst=
    this.getData()
    this.getApi()
    this.getmenu()
  },
  methods: {
    getmenu() {
      let data =JSON.parse(localStorage.getItem('routes'))
      this.menuLIst=data.filter(item => item.hidden === undefined)
      this.menuLIst.forEach(item=>{
        if(item.children!=undefined){
          item.children=item.children.filter(items=>{
            return items.hidden==undefined
          })
        }
      })
      console.log('getmenu',this.menuLIst)
    },
    checkchange() {
      let data = this.$refs.tree.getCheckedNodes().filter(item => item['path'] != undefined).map(item => {
        return {
          path: item.path,
          method: item.method,
          label: item.brief
        }
      })
      this.request('admin/apiAuthority/', 'POST', { casbinInfos: data, user: this.user.toString() }).then(res => {
        if (res.errno == 0) {
          this.$message.success(res.errmsg);

        } else {
          this.$message.error(res.errmsg);
        }
        this.getData()
        this.drawer = false
      })
    },
    checkchanges() {
      let data = this.$refs.trees.getCheckedNodes()
      data=data.filter(item=>{
        return item.redirect==undefined
      })
      let datas=this.menuLIst
      data.forEach(item=>{
        datas.forEach(items=>{
          if(items.children!=undefined){
          console.log(items)
            items.children.forEach(itemss=>{
                if(itemss.name==item.name){
                  console.log("内",itemss.name)
                  itemss['hidden']=false
                }
            })
          }
        })
      })
      datas.forEach(item=>{
          if(item.children!=undefined){
            item.children=item.children.filter(items=>{
              return !items.hidden&&items.hidden!=undefined
            })
            console.log(item.name,item.children.length)
            if(!item.children.length){
              item['hidden']=true
            }
          }else{
            item['hidden']=true
          }
      })
      this.user.explain=JSON.stringify(datas)
      this.request('business/adminManage/', 'put',  this.user).then(res => {
        if (res.errno == 0) {
          this.$message.success(res.errmsg);
        } else {
          this.$message.error(res.errmsg);
        }

        this.drawerss = false
        this.drawers = false
        this.menuShow=false
        this.user=[]
        this.menuLIst=[]
        this.menuchecklist=[]
      })
      setTimeout(() => {
        this.getData()
        this.getApi()
        this.getmenu()
      }, 1000);
    },
    getApi() {
      this.request('business/apiManage/', 'get', { page: this.query.pageIndex, size: 1000 }).then(res => {
        let arr = {}
        res.data.data.forEach(item => {
          if (Array.isArray(arr[item.group])) {
            arr[item.group].push(item)
          } else {
            arr[item.group] = []
            arr[item.group].push(item)
          }

        });
        console.log(arr)
        for (let i in arr) {
          this.apiLIst.push({
            brief: i,
            children: arr[i]
          })
        }
      })
    },
    opendrawer(id) {
      this.drawer = true
      this.user = id
      this.request('admin/apiAuthority/', 'get', { casbinInfos: [1], user: id.toString() }).then(res => {
        this.checklist = res.data.map(item => item[3])
      })
    },
    openmenu(id){
      this.user = id
      let explain=id.explain?JSON.parse(id.explain):[]
      let check=[]
      if(id.explain){
        explain.forEach(items=>{
        if(items.children!=undefined){
          items.children.forEach(itemss=>{
            check.push(itemss.name)
          })
        }else{
          if(!items.hidden&&items.hidden!=undefined){
            check.push(items.name)
          }
        }
      })
      }

      this.menuchecklist=check
      this.menuShow = true
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.form.img = this.url + res.key;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeupload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
        return false;
      }
      if (file.size / 1024 / 1024 > 1) {
        this.$message.error('上传图标大小不能超过 1M!');
        return false;
      }
      let types = file.name.split('.')//获取图片格式
      this.upimg.key = 'template/home/' + new Date().valueOf() + '.' + types[types.length - 1];
    },
    //获取数据
    getData() {
      	this.loading=true
      this.request('business/adminManage/', 'get', { page: this.query.pageIndex, size: this.query.pageSize }).then(res => {
        console.log(res.data.data)

        this.tableData =res.data.data
        this.pageTotal = res.data.total
      })
      	this.loading=false
    },
    // 编辑
    handleEdit(e) {
      this.editVisible = true;
      this.form = e;
      this.imageUrl = e.img;
      this.type = 1
    },
    cancel() {
      this.editVisible = false;
      this.form = {
        mobile: '',
        name: '',
        password: '',
        jurisdiction: ''
      };
      this.getData();
    },
    // 修改排序
    operations(e, code) {
      console.log(e)
      e.sort = Number(e.sort)
      console.log(e)
      this.request('business/adminManage/', 'put', e).then(res => {
        if (res.errno == 0) {
          this.$message.success(res.errmsg);
        } else {
          this.$message.error(res.errmsg);
        }
      });
      this.editVisible = false;
      this.getData();
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.request('business/adminManage/', 'delete', { ID: row.ID }).then(res => {
            if (res.errno == 0) {
              this.$message.success(res.errmsg);
              this.tableData.splice(index, 1)
              this.getData()
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 添加
    addregion() {
      this.form = {
        mobile: '',
        name: '',
        password: '',
        jurisdiction: ''
      };
      this.type = 0
      this.imageUrl = '';
      this.editVisible = true;
    },

    // 添加/修改
    saveEdit() {
      if (!this.form.name) return this.$message.error('请输入姓名');
      if (!this.form.mobile) return this.$message.error('请输入电话');
      if (!(/^1[3456789]\d{9}$/).test(this.form.mobile)) return this.$message.error('请输入正确电话');
      if (this.type) {
        if (this.form.password && this.form.password.length < 6) return this.$message.error('请输入最短6位密码');
      } else {
        if (!this.form.password || this.form.password.length < 6) return this.$message.error('请输入最短6位密码');
      }

      if (!this.form.jurisdiction) return this.$message.error('请输入标签');
      this.request('business/adminManage/', this.type ? 'put' : 'post', this.form).then(res => {
        if (res.errno == 0) {
          this.$message.success(res.errmsg);
          this.form = {
            mobile: '',
            name: '',
            password: '',
            jurisdiction: ''
          };
          this.getData()
        } else {
          this.$message.error(res.errmsg);
        }
      });
      this.editVisible = false;
      this.getData();
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, 'pageIndex', val);
      this.getData();
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.el-upload--text {
  width: 200px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;

  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  /* width: 100px; */
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 178px;
  display: block;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 60px;
  height: 60px;

  .el-image img {
    object-fit: cover;
  }
}

/* 设置分页按钮样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.drawerbox {
  padding: 20px;

  .drawerboxs {
    margin-top: 20px;
    font-size: 20px;

    .title {
      font-size: 20px;
      font-weight: bold;
    }

    .brief {
      margin-top: 10px;
    }
  }
}
</style>
